package com.liull.netty.nio.bytebuffer;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: liull
 * @Description: 读写文件内容
 * @Date: Created in 20:35 2021/7/21
 * @Modified By:
 */
public class ByteBufferTest {
    public static void main(String[] args) {
        try (RandomAccessFile raf = new RandomAccessFile("bytebuffer.txt", "rw")) {
            FileChannel channel = raf.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(4);
            // 写入模式
            while (true) {
                int read = channel.read(buffer);
                if (read == -1) {
                    break;
                }
                // 切换模式
                buffer.flip();
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    System.out.println((char) b);
                }
                // 切换回写模式
                buffer.clear();
            }

        } catch (IOException e) {

        }
    }
}
